/** 利用localStorage实现跨窗口通信
 * @eventName string ：监听名称
 * @callBack Function ：回调函数
 * @val 任意值：发送事件携带的值
 * */
class StorageEvent {
  // 返回事件队列
  static eventQueue() {
    return this.eventQueue;
  }
  constructor() {
    this.eventQueue = {};
    let _this = this;
    window.addEventListener('storage', function(event) {
      // 1. 获取key值
      let key = event.key;
      // 2. 根据key值获取注册的回调函数
      let callBackArr = _this.eventQueue[key] || [];
      // 3. 获取回调值
      let val = localStorage.getItem(key + '_val');
      try {
        val = JSON.parse(val);
      } catch (e) {}
      callBackArr.forEach(cb => {
        cb.call(this, val);
      });
    });
  }
  // 注册监听
  addStorageEvent(eventName, callBack) {
    this.eventQueue[eventName] = this.eventQueue[eventName] || [];
    this.eventQueue[eventName].push(callBack);
  }
  // 发送事件
  sendStorageEvent(eventName, val = '') {
    if (typeof val === 'object') {
      val = JSON.stringify(val);
    }
    localStorage.setItem(eventName + '_val', val);
    localStorage.setItem(eventName, Date().valueOf());
  }
}
export const storageEvent = new StorageEvent();
Vue.prototype.storageEvent = storageEvent;